﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Forum.BLL.Board;
using Forum.Entity.Board;
using Forum.BLL.Group;
using Forum.Entity.Group;
using System.Data;
using Forum.BLL.Member;
using Forum.Entity.Member;
using Frame.Lib.Core.Right;
using Frame.Lib.Web;
using Frame.Lib.Utilities;
using Frame.Lib.Common;
using Frame.Lib.Enums;

namespace Forum.Web.Admin.UForum.Board
{
    public partial class Edit : PageEdit
    {
        private BoardBO Board
        {
            get
            {
                return BoardBO.Instance<BoardBO>();
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            CssFileManager.AddCssFile(CssFile.tab2);
            if (!IsPostBack)
            {
                WebUtil.BindListControlWithEnum(State, typeof(BoardState));

                if (!string.IsNullOrEmpty(this.PKID))
                {
                    DispInfo();
                }
                else
                {
                    UpperID.Value = StrUtil.DecryptDES(Request["UpperID"]);
                    lblUpperName.Text = Board.GetName(UpperID.Value);
                    //Orders.Text = Board.GetMaxOrder().ToString();
                }
            }

            BindList();
            BindRight();
            JSUtil.ExcuteJS("restore();");
        }

        private void DispInfo()
        {
            BoardInfo info = Board.GetInfo(PKID);
            EntityUtil.SetControl(pnlMain, info);
            if (info.UpperID == 0)
            {
                lblUpperName.Text = "顶级版块没有上级版块";
            }
            else
            {
                lblUpperName.Text = Board.GetName(info.UpperID);
            }

            //处理权限            

            string rightIDs = ",";
            //浏览
            SetIDWidthRight(RecordRightName.浏览论坛, ref rightIDs, RightOwnerType.ForumMemberGroup);

            //发新话题
            SetIDWidthRight(RecordRightName.发新话题, ref rightIDs, RightOwnerType.ForumMemberGroup);

            //发表回复
            SetIDWidthRight(RecordRightName.发表回复, ref rightIDs, RightOwnerType.ForumMemberGroup);

            //下载附件
            SetIDWidthRight(RecordRightName.下载附件, ref rightIDs, RightOwnerType.ForumMemberGroup);

            //上传附件
            SetIDWidthRight(RecordRightName.上传附件, ref rightIDs, RightOwnerType.ForumMemberGroup);


            if (rightIDs == ",")
            {
                rightIDs = "";
            }

            hidGroupRight.Value = rightIDs;

            //特殊会员权限处理
            rightIDs = ",";

            //浏览
            SetIDWidthRight(RecordRightName.浏览论坛, ref rightIDs, RightOwnerType.ForumMember);

            //发新话题
            SetIDWidthRight(RecordRightName.发新话题, ref rightIDs, RightOwnerType.ForumMember);

            //发表回复
            SetIDWidthRight(RecordRightName.发表回复, ref rightIDs, RightOwnerType.ForumMember);

            //下载附件
            SetIDWidthRight(RecordRightName.下载附件, ref rightIDs, RightOwnerType.ForumMember);

            //上传附件
            SetIDWidthRight(RecordRightName.上传附件, ref rightIDs, RightOwnerType.ForumMember);

            if (rightIDs == ",")
            {
                rightIDs = "";
            }

            hidMemberRight.Value = rightIDs;

        }

        private void SetIDWidthRight(RecordRightName rightName, ref string rightIDs, RightOwnerType ownerType)
        {
            RecordRightBO right = new RecordRightBO(Forum.DAL.TableName.BoardRight);
            List<int> groupIDs = right.GetOwnerIDs(int.Parse(this.PKID), rightName, ownerType);
            foreach (int id in groupIDs)
            {
                rightIDs += id + "_" + (int)rightName + ",";
            }
        }

        private void BindRight()
        {
            IEnumerable<EnumInfo> rights = ConvertUtil.ConvertEnum(typeof(RecordRightName)).Where(T => T.ID >= (int)RecordRightName.浏览论坛 && T.ID <= (int)RecordRightName.上传附件);
            rptRight.DataSource = rights;
            rptRight.DataBind();

            rptUser.DataSource = rights;
            rptUser.DataBind();

            GroupBO group = new GroupBO();
            IEnumerable<GroupInfo> list = group.GetList();

            DataTable dt = new DataTable();
            dt.Columns.Add("ID", typeof(int));
            dt.Columns.Add("Name", typeof(string));

            int i = 0;
            foreach (EnumInfo info in rights)
            {
                dt.Columns.Add("f" + i);
                i++;
            }

            //构建table
            foreach (GroupInfo info in list)
            {
                DataRow dr = dt.NewRow();
                dr["ID"] = info.ID;
                dr["Name"] = info.Name;

                i = 0;
                foreach (EnumInfo field in rights)
                {
                    dr["f" + i] = info.ID + "_" + field.ID;
                    i++;
                }

                dt.Rows.Add(dr);
            }

            lv.DataSource = dt.DefaultView;
            lv.DataBind();

            //构建用户权限的table
            if (!string.IsNullOrEmpty(PKID))
            {
                RecordRightBO right = new RecordRightBO(Forum.DAL.TableName.BoardRight);
                List<int> memberIDs = right.GetOwnerIDs(int.Parse(PKID), RecordRightName.发表回复, RightOwnerType.ForumMember);
                //Utils
                CommUtil.MergeList<int>(memberIDs, right.GetOwnerIDs(int.Parse(PKID), RecordRightName.发新话题, RightOwnerType.ForumMember));
                CommUtil.MergeList<int>(memberIDs, right.GetOwnerIDs(int.Parse(PKID), RecordRightName.浏览论坛, RightOwnerType.ForumMember));
                CommUtil.MergeList<int>(memberIDs, right.GetOwnerIDs(int.Parse(PKID), RecordRightName.上传附件, RightOwnerType.ForumMember));
                CommUtil.MergeList<int>(memberIDs, right.GetOwnerIDs(int.Parse(PKID), RecordRightName.下载附件, RightOwnerType.ForumMember));
                MemberBaseBO member = new MemberBaseBO();
                List<MemberBaseInfo> mems = member.GetList(memberIDs);
                dt.Rows.Clear();
                foreach (MemberBaseInfo info in mems)
                {
                    DataRow dr = dt.NewRow();
                    dr["ID"] = info.ID;
                    dr["Name"] = info.LoginName;
                    i = 0;
                    foreach (EnumInfo field in rights)
                    {
                        dr["f" + i] = info.ID + "_" + field.ID;
                        i++;
                    }

                    dt.Rows.Add(dr);
                }
                lvUserRight.DataSource = dt;
                lvUserRight.DataBind();
            }

        }

        private void BindList()
        {
            List<EnumInfo> list = ConvertUtil.ConvertEnum(typeof(BoardTab));
            rpt.DataSource = list;
            rpt.DataBind();

        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            int upperID = int.Parse(UpperID.Value);
            bool flag = Board.Exist(upperID, Name.Text, this.PKID);
            if (flag)
            {
                JSUtil.Alert("该版块已存在");
            }
            else
            {
                BoardInfo info = this.Board.GetInfo(PKID);
                EntityUtil.SetEntity(pnlMain, info);
                if (upperID != Constants.TREE_ROOT_UPPER_ID)
                {
                    BoardInfo parentInfo = Board.GetInfo(upperID);
                    info.Depth = (int)parentInfo.Depth + 1;
                    info.Path = parentInfo.Path.ToString() + parentInfo.ID + ",";
                }

                if (string.IsNullOrEmpty(this.PKID))
                {
                    info.Orders = Board.GetMaxOrder();

                }

                Board.Save(info);

                //保存组权限
                SaveRight(hidGroupRight, info.ID, RightOwnerType.ForumMemberGroup);


                //保存特殊用户权限
                SaveRight(hidMemberRight, info.ID, RightOwnerType.ForumMember);

                JSUtil.RefreshView();

            }


        }


        private void SaveRight(HiddenField hid, int bindID, RightOwnerType ownerType)
        {
            RecordRightBO right = new RecordRightBO(Forum.DAL.TableName.BoardRight);

           

            List<int> lstBrowseGroups = new List<int>();//浏览
            List<int> lstNewGroups = new List<int>();//发新话题
            List<int> lstReplyGroups = new List<int>();//回复
            List<int> lstDownGroups = new List<int>();//下载
            List<int> lstUpGroups = new List<int>();//上传


            string[] rights = hid.Value.Trim(',').Split(',');
            foreach (string str in rights)
            {
                if (str == "")
                {
                    continue;
                }
                int groupID = int.Parse(str.Split('_')[0]);
                RecordRightName rightName = (RecordRightName)int.Parse(str.Split('_')[1]);

                switch (rightName)
                {
                    case RecordRightName.浏览论坛:
                        lstBrowseGroups.Add(groupID);
                        break;
                    case RecordRightName.发新话题:
                        lstNewGroups.Add(groupID);
                        break;
                    case RecordRightName.发表回复:
                        lstReplyGroups.Add(groupID);
                        break;
                    case RecordRightName.下载附件:
                        lstDownGroups.Add(groupID);
                        break;
                    case RecordRightName.上传附件:
                        lstUpGroups.Add(groupID);
                        break;
                }
            }

            right.SaveOwnerIDs(lstBrowseGroups, bindID, RecordRightName.浏览论坛, ownerType);
            right.SaveOwnerIDs(lstNewGroups, bindID, RecordRightName.发新话题, ownerType);
            right.SaveOwnerIDs(lstReplyGroups, bindID, RecordRightName.发表回复, ownerType);
            right.SaveOwnerIDs(lstDownGroups, bindID, RecordRightName.下载附件, ownerType);
            right.SaveOwnerIDs(lstUpGroups, bindID, RecordRightName.上传附件, ownerType);

        }
    }
}